import { useLocalStorage } from "@vueuse/core";
const token = useLocalStorage("access_token", "");
const Request = ({ url, method = "post", data = {},onProgress = e => e, headers= {}}) => {
    headers["Authorization"] = `${token.value}`
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.upload.onprogress = onProgress;
        xhr.open(method, url);
        Object.keys(headers).forEach(key =>
            xhr.setRequestHeader(key, headers[key])
        );
        if (method.toLowerCase() === 'post' || method.toLowerCase() === 'put') {
            xhr.send(data as any);
        } else {
            xhr.send(); // GET请求不带数据
        }
        xhr.onload = e => {
            if (xhr.status >= 200 && xhr.status < 300) {
                resolve({
                    data: xhr.response,
                    status: xhr.status,
                    statusText: xhr.statusText
                });
            } else {
                reject({
                    error: `Request failed with status ${xhr.status}`,
                    status: xhr.status,
                    statusText: xhr.statusText
                });
            }
        };
        xhr.onerror = e => {
            reject({
                error: 'Network Error',
                status: xhr.status,
                statusText: xhr.statusText
            });
        }
    });
}

export default Request;